#include "game2.h"

int puzzle[PUZZLE_SIZE][PUZZLE_SIZE];
int empty_row, empty_col;
lv_obj_t *cells[PUZZLE_SIZE][PUZZLE_SIZE];
lv_obj_t *game_area;
lv_obj_t *moves_count_label;
int moves_count = 0;

/* 检查游戏是否已完成 */
static bool is_game_completed(void) {
    int expected = 1;
    for (int i = 0; i < PUZZLE_SIZE; i++) {
        for (int j = 0; j < PUZZLE_SIZE; j++) {
            if (i == PUZZLE_SIZE - 1 && j == PUZZLE_SIZE - 1) {
                if (puzzle[i][j] != 0) return false;
            } else {
                if (puzzle[i][j] != expected++) return false;
            }
        }
    }
    return true;
}

static void swap_data(int row1, int col1, int row2, int col2) {
    int temp = puzzle[row1][col1];
    puzzle[row1][col1] = puzzle[row2][col2];
    puzzle[row2][col2] = temp;
}

void game2_over_ui(void) {
     // 清空屏幕
    lv_obj_clean(lv_scr_act());
    
    // 创建一个标签显示分数
    lv_obj_t * main_window = lv_obj_create(NULL);

	lv_obj_t * img = lv_img_create(main_window);
	lv_img_set_src(img, "S:/bmp/game_end.png");
	lv_obj_set_size(img, 800, 480);
	lv_obj_align(img,LV_ALIGN_TOP_LEFT,0,0);

	lv_obj_t *label = lv_label_create(main_window);
    char score_str[20];	
    sprintf(score_str, "Your number of moves is %d", moves_count
);
    lv_label_set_text(label, score_str);
	lv_obj_set_style_text_font(label, &lv_font_montserrat_20, 0); 
	lv_obj_set_style_text_color(label, lv_color_hex(0xffffff), 0); 
    lv_obj_align(label, LV_ALIGN_TOP_MID, 0, 0);
    
    // 创建一个关闭按钮
    lv_obj_t * close_btn = lv_btn_create(main_window);
    lv_obj_set_size(close_btn, 50, 50);
	lv_obj_set_style_bg_color(close_btn, lv_color_hex(0xff0000), 0);
    lv_obj_align(close_btn, LV_ALIGN_TOP_RIGHT, -10, 10);

    lv_obj_t * btn_label = lv_label_create(close_btn);
    lv_label_set_text(btn_label, LV_SYMBOL_CLOSE);
    lv_obj_set_style_text_color(btn_label, lv_color_hex(0xffffff), 0);
    lv_obj_center(btn_label);

	lv_obj_add_event_cb(close_btn, game_event, LV_EVENT_SHORT_CLICKED, NULL);

	lv_scr_load(main_window);
}
   


/* 交换两个单元格 */
static void swap_cells(int row1, int col1, int row2, int col2) {
    int temp = puzzle[row1][col1];
    puzzle[row1][col1] = puzzle[row2][col2];
    puzzle[row2][col2] = temp;

    /* 更新显示 */
    char buf[10];
    if (puzzle[row1][col1] == 0) {
        lv_label_set_text(lv_obj_get_child(cells[row1][col1], 0), "");
    } else {
        snprintf(buf, sizeof(buf), "%d", puzzle[row1][col1]);
        lv_label_set_text(lv_obj_get_child(cells[row1][col1], 0), buf);
    }

    if (puzzle[row2][col2] == 0) {
        lv_label_set_text(lv_obj_get_child(cells[row2][col2], 0), "");
    } else {
        snprintf(buf, sizeof(buf), "%d", puzzle[row2][col2]);
        lv_label_set_text(lv_obj_get_child(cells[row2][col2], 0), buf);
    }

    moves_count++;
    char count_buf[20];
    snprintf(count_buf, sizeof(count_buf), "移动次数: %d", moves_count
);
    lv_label_set_text(moves_count_label, count_buf);

    /* 检查游戏是否完成 */
    if (is_game_completed()) {
        game2_over_ui();
    }
}

/* 单元格点击事件处理函数 */
static void cell_event_handler(lv_event_t *e) {
    lv_obj_t *obj = lv_event_get_target(e);
    int row = (int)lv_obj_get_user_data(obj) / PUZZLE_SIZE;
    int col = (int)lv_obj_get_user_data(obj) % PUZZLE_SIZE;

    /* 检查是否可以移动 */
    if ((row == empty_row && (col == empty_col - 1 || col == empty_col + 1)) ||
        (col == empty_col && (row == empty_row - 1 || row == empty_row + 1))) {
        swap_cells(row, col, empty_row, empty_col);
        empty_row = row;
        empty_col = col;
    }
}

/* 初始化游戏区域 */
void init_game_area(void) {
    /* 创建游戏区域 */
    game_area = lv_obj_create(lv_scr_act());
    lv_obj_set_size(game_area, GAME_AREA_SIZE, GAME_AREA_SIZE);
    lv_obj_center(game_area);
    lv_obj_set_style_bg_color(game_area, lv_color_hex(0xbbada0), 0);
    lv_obj_set_style_radius(game_area, 10, 0);

    /* 创建移动次数标签 */
    moves_count_label = lv_label_create(lv_scr_act());
    lv_label_set_text(moves_count_label, "移动次数: 0");
    lv_obj_align_to(moves_count_label, game_area, LV_ALIGN_OUT_BOTTOM_MID, 0, 20);
}

void update_cell_display(void) {
    for (int i = 0; i < PUZZLE_SIZE; i++) {
        for (int j = 0; j < PUZZLE_SIZE; j++) {
            lv_obj_t *cell = cells[i][j];
            lv_obj_t *label = lv_obj_get_child(cell, 0);
            
            if (puzzle[i][j] == 0) {
                lv_obj_set_style_bg_color(cell, lv_color_hex(0xece0d1), 0);
                lv_label_set_text(label, "");
            } else {
                char buf[10];
                snprintf(buf, sizeof(buf), "%d", puzzle[i][j]);
                lv_label_set_text(label, buf);
            }
        }
    }
}

/* 创建游戏单元格 */
void create_cells(void) {
    static lv_style_t cell_style;
    lv_style_init(&cell_style);
    lv_style_set_bg_color(&cell_style, lv_color_hex(0xcdc1b4));
    lv_style_set_radius(&cell_style, 5);
    lv_style_set_text_font(&cell_style, &lv_font_montserrat_30);
    lv_style_set_text_color(&cell_style, lv_color_hex(0x776e65));

    for (int i = 0; i < PUZZLE_SIZE; i++) {
        for (int j = 0; j < PUZZLE_SIZE; j++) {
            cells[i][j] = lv_obj_create(game_area);
            lv_obj_add_style(cells[i][j], &cell_style, 0);
            lv_obj_set_size(cells[i][j], CELL_SIZE, CELL_SIZE);
            lv_obj_set_pos(cells[i][j], j*(CELL_SIZE+CELL_MARGIN), i*(CELL_SIZE+CELL_MARGIN));
            lv_obj_set_user_data(cells[i][j], (void*)(i*PUZZLE_SIZE + j));
            lv_obj_add_event_cb(cells[i][j], cell_event_handler, LV_EVENT_CLICKED, NULL);

            // 创建标签，但不设置文本（由update_cell_display统一设置）
            lv_obj_t *label = lv_label_create(cells[i][j]);
            lv_obj_center(label);
        }
    }
}

/* 初始化游戏数据 */
void init_game_data(void) {
    // 初始化拼图为完成状态（不变）
    int value = 1;
    for (int i = 0; i < PUZZLE_SIZE; i++) {
        for (int j = 0; j < PUZZLE_SIZE; j++) {
            if (i == PUZZLE_SIZE - 1 && j == PUZZLE_SIZE - 1) {
                puzzle[i][j] = 0;
                empty_row = i;
                empty_col = j;
            } else {
                puzzle[i][j] = value++;
            }
        }
    }

    // 打乱拼图：使用swap_data（仅操作数据，不碰UI）
    srand(time(NULL));
    int moves = 100;
    while (moves > 0) {
        int direction = rand() % 4;
        int new_row = empty_row;
        int new_col = empty_col;

        switch (direction) {
            case 0: new_row--; break;
            case 1: new_row++; break;
            case 2: new_col--; break;
            case 3: new_col++; break;
        }

        if (new_row >= 0 && new_row < PUZZLE_SIZE && new_col >=0 && new_col < PUZZLE_SIZE) {
            swap_data(new_row, new_col, empty_row, empty_col);  // 替换为swap_data
            empty_row = new_row;
            empty_col = new_col;
            moves--;
        }

        // 重置移动次数（此时还未创建UI，仅更新变量）
        moves_count= 0;
    }
}

/* 重新开始游戏 */
static void restart_game(lv_event_t *e) {
    /* 清除旧的单元格 */
    for (int i = 0; i < PUZZLE_SIZE; i++) {
        for (int j = 0; j < PUZZLE_SIZE; j++) {
            lv_obj_del(cells[i][j]);
        }
    }

    /* 初始化游戏数据并创建新的单元格 */ 
    moves_count= 0;
    init_game_data();
    create_cells();
    update_cell_display();
}

/* 创建游戏控制按钮 */
void create_control_buttons(void) {
    lv_obj_t *restart_btn = lv_btn_create(lv_scr_act());
    lv_obj_set_size(restart_btn, 120, 40);
    lv_obj_align_to(restart_btn, game_area, LV_ALIGN_OUT_TOP_MID, 0, 0);
    lv_obj_set_style_bg_color(restart_btn, lv_color_hex(0xff0000), 0);
    lv_obj_add_event_cb(restart_btn, restart_game, LV_EVENT_CLICKED, NULL);

    lv_obj_t *restart_label = lv_label_create(restart_btn);
    lv_label_set_text(restart_label, LV_SYMBOL_REFRESH);
    lv_obj_set_style_text_color(restart_label, lv_color_hex(0xffffff), 0);
    lv_obj_center(restart_label);

     lv_obj_t * close_btn = lv_btn_create(lv_scr_act());
    lv_obj_set_size(close_btn, 50, 50);
	lv_obj_set_style_bg_color(close_btn, lv_color_hex(0xff0000), 0);
    lv_obj_align(close_btn, LV_ALIGN_TOP_RIGHT, -10, 10);

    lv_obj_t * btn_label = lv_label_create(close_btn);
    lv_label_set_text(btn_label, LV_SYMBOL_CLOSE);
    lv_obj_set_style_text_color(btn_label, lv_color_hex(0xffffff), 0);
    lv_obj_center(btn_label);

	lv_obj_add_event_cb(close_btn, game_event, LV_EVENT_SHORT_CLICKED, NULL);
}

/* 创建游戏标题 */
void create_game_title(void) {
    lv_obj_t *title_label = lv_label_create(lv_scr_act());
    lv_label_set_text(title_label, "数字华容道");
    lv_obj_set_style_text_font(title_label, &lv_font_montserrat_30, 0);
    lv_obj_align_to(title_label, game_area, LV_ALIGN_OUT_TOP_MID, 0, -120);
}
  